<template>
  <div>
    <el-row style="margin-bottom: 30px">
      <el-col :span="24">
        <el-button type="primary" :icon="Edit" @click="handInsertOne">新增一级分类</el-button>
      </el-col>
    </el-row>
    <el-tree
        :data="state.data"
        :props="defaultProps"
        node-key="categoryId"
        :default-expand-all=true
        :expand-on-click-node='false'
        :render-content="renderContent"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <a @click="update(data)"> 修改 </a>
            <a style="margin-left: 8px" @click="remove(node, data)"> 删除 </a>
          </span>
        </span>
      </template>
    </el-tree>
  </div>

  <el-dialog
      v-model="state.dialogVisible"
      :title="state.dialogTypeName + '分类名称'"
      width="500"
  >
    <el-input v-model="state.updateFrom.categoryName" style="width: 240px" placeholder="请输入分类名称"/>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="fromBtn(0)">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <!--    新增-->
  <el-dialog
      v-model="state.insertDialogVisible"
      :title="state.insertFrom.level === 1 ? '新增一级分类': '新增二级分类'"
      width="500"
  >
    <el-form :model="state.insertFrom" label-width="120px">
      <el-form-item label="分类名称">
        <el-input v-model="state.insertFrom.categoryName"/>
      </el-form-item>
      <el-form-item label="分类排序">
        <el-input v-model="state.insertFrom.sort" placeholder="值越小，级别越高"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="insert">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup lang="ts">
import {Edit} from '@element-plus/icons-vue';
import {ElButton} from 'element-plus';
import {postRequest} from "~/composables/http";

//更换默认节点名称
const defaultProps = {
  children: 'getCategoryVo',
  label: 'categoryName'
};

const state = reactive({
  dialogTypeName: '',
  dialogVisible: false,
  insertDialogVisible: false,
  fromType: 0,
  data: [],
  updateFrom: {
    categoryId: '',
    categoryName: '',
    level: 999
  },
  insertFrom: {
    sort: 1,
    categoryId: '',
    categoryName: '',
    level: 999,
		channel: 2,
  }

});
const renderContent = (h, {node, data, store}) => {
  return h('span', [
    h('span', node.label),
    node.level === 1 ? h(ElButton, {
      onClick: () => handleAdd(data),
      type: 'text',
      size: 'small'
    }, '新增') : null,
    h(ElButton, {
      onClick: () => update(data),
      type: 'text',
      size: 'small'
    }, '修改'),
    h(ElButton, {
      onClick: () => remove(node, data),
      type: 'text',
      size: 'small'
    }, '删除')
  ])
}

/**
 * 点击新增一级分类操作
 */
function handInsertOne() {
  //一级分类
  state.insertFrom.level = 1
  state.insertDialogVisible = true
}

//新增提交
function insert() {
  if (state.insertFrom.level === 1) {
		postRequest("/api/admin/category/categorySave", state.insertFrom).then((res: any) => {
      if (res.code === 200) {
        init();
        ElMessage.success('一级分类新增成功');
        state.insertDialogVisible = false;
      } else {
        ElMessage.error(res.msg);
      }
    })
  } else if (state.insertFrom.level === 2) {
		postRequest("/api/admin/category/categorySave", state.insertFrom).then((res: any) => {
      if (res.code === 200) {
        init();
        ElMessage.success('二级分类新增成功');
        state.insertDialogVisible = false;
        return;
      } else {
        ElMessage.error(res.msg);
        return;
      }
    })
  } else {
    ElMessage.error("分类级别不合法");
  }

}

function handleAdd(data: any) {
  state.insertDialogVisible = true
  state.insertFrom.categoryId = data.categoryId
  state.insertFrom.level = 2
}

//修改
function update(data: any) {
  state.dialogTypeName = '修改';
  state.dialogVisible = true;
  state.updateFrom.categoryId = data.categoryId;
  state.updateFrom.categoryName = data.categoryName;
  if (data.getCategoryVo === null) {
    state.updateFrom.level = 2;
  } else {
    state.updateFrom.level = 1;
  }
  state.fromType = 0;
}

/**
 * 删除
 */
function remove(node: any, data: any) {
  if (node.level === 1) {
    if (data.getCategoryVo.length !== 0) {
      ElMessage.error('一级分类有下级分类不能删除');
      return;
    }
		postRequest('/api/admin/category/categoryDel', {
      'categoryId': data.categoryId,
      'level': 1
    }).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('删除成功');
        init();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
  if (node.level === 2) {
		postRequest('/api/admin/category/categoryDel', {
      'categoryId': data.categoryId,
      'level': 2
    }).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('删除成功');
        init();
      } else {
        ElMessage.error(res.msg);
      }


    });
  }
}

function fromBtn(type: number) {
  if (type === 0) {
    if (state.updateFrom.categoryId === '' && state.updateFrom.categoryName === '') {
      ElMessage.error('分类编号或者名称不能为空');
      return;
    }
		postRequest('/api/admin/category/categoryUpdate', state.updateFrom).then((res:any) => {
      if (res.code === 200) {
        console.log(res);
        init();
        ElMessage.success('修改成功');
        state.dialogVisible = false;
      } else {
        ElMessage.error(res.msg);
      }
    });
  }
}


function init() {

	postRequest("/api/category/categoryList", { channel: 2 }).then((res: any) => {
    state.data = res.data;
		if (state.data.length > 0) {
			state.data.forEach((item: any) => {
				clickCategory(item);
			});
		}
  });

}

function clickCategory(item: any) {
	postRequest("/api/category/clickCategory", {
		firstSysId: item.categoryId,
	})
		.then((res: any) => {
			if (res.code == 200) {
				item.getCategoryVo = res.data;
			}
		});
}



onMounted(()=>{
	init();
})
</script>
<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
